<template>
	<view class="content">
		<button type="primary" @click="chooseImage">选择打卡截图</button>

		<view class="SelectTime">
			<view class="PriceLabel">
				上午
			</view>
			<view class="PriceText">
				{{amTime}}{{amDuration}}
			</view>
		</view>

		<view class="SelectTime">
			<view class="PriceLabel">
				下午
			</view>
			<view class="PriceText">
				{{pmTime}}{{pmDuration}}
			</view>
		</view>

		<view class="SelectTime">
			<view class="PriceLabel">
				晚上
			</view>
			<view class="PriceText">
				{{niTime}}
			</view>
		</view>

		<view class="SelectTime">
			<view class="PriceLabel PriceLabel2">
				白天已干
			</view>
			<view class="PriceText">
				{{duration}}
			</view>
		</view>

		<view class="SelectTime">
			<view class="PriceLabel PriceLabel2">
				最早撤退
			</view>
			<view class="PriceText">
				{{lastTime}}
			</view>
		</view>

	</view>
</template>

<script>
	import {
		toBase64
	} from '@/utils/convert.js'
	export default {
		data() {
			return {
				amTime: "",
				amDuration: "",

				pmTime: "",
				pmDuration: "",

				niTime: "",
				niDuration: "",

				duration: "",
				lastTime: ""
			};
		},
		methods: {
			// 选择本地图片
			chooseImage() {
				let self = this
				uni.chooseImage({
					count: 1,
					success: (ress) => {
						// console.log(ress)
						uni.showLoading({
							title: '正在识别中...'
						})
						// 下面将图片本地路径转base64
						toBase64(ress.tempFilePaths[0]).then((res) => {
							// console.log(res)
							self.uploadImage(res)
						})
					},
					fail(err) {
						uni.hideLoading()
						console.log(err)
					}
				})
			},

			uploadImage(path) {
				uni.request({
					url: 'http://118.178.134.167/baiduapi/ocr',
					data: {
						image: path
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.hideLoading()
						// console.log(res.data.words_result)
						this.jisuan(res.data.words_result)
					},
					fail(err) {
						// uni.hideLoading()
						console.log(err)
						uni.showToast({
							title: `读取失败`,
							icon: 'error'
						})
					}
				})
			},

			parseTime(timeStr) {
				const [hours, minutes] = timeStr.split(":").map(Number);
				return hours * 60 + minutes; // 将时间转换为分钟数
			},
			formatTime(minutes) {
				const hours = Math.floor(minutes / 60);
				const mins = minutes % 60;
				return `${hours}小时${mins}分`;
			},

			jisuan(words) {
				let times = [];
				for (let i = 0; i < words.length; i++) {
				    const currentEntry = words[i];
				    const regexWithTime = /签退(\d{1,2}[:：]\d{2})|签到(\d{1,2}[:：]\d{2})/;
				    const regexOnlyAction = /^(签到|签退)$/;
				    const regexOnlyTime = /(\d{1,2}[:：]\d{2})/;
				
				    let matchWithTime = regexWithTime.exec(currentEntry.words);
				    let matchOnlyAction = regexOnlyAction.exec(currentEntry.words);
				
				    if (matchWithTime && (matchWithTime[1] || matchWithTime[2])) {
				        // 当前条目包含签到或签退并且有具体时间
				        times.push(matchWithTime[1] || matchWithTime[2]);
				    } else if (matchOnlyAction && i + 1 < words.length) {
				        // 当前条目仅包含签到或签退，并且还有下一个条目
				        let nextEntry = words[i + 1];
				        let matchOnlyTime = regexOnlyTime.exec(nextEntry.words);
				        if (matchOnlyTime) {
				            times.push(matchOnlyTime[1]);
				            i++; // 跳过下一个条目，因为它已经被处理
				        }
				    }
				}
				console.log(times);
				// const times = words.map(str => {
				// 	// console.log(str)
				// 	const regex = /签退(\d{1,2}[:：]\d{2})|签到(\d{1,2}[:：]\d{2})/;
				// 	const match = regex.exec(str.words);
				// 	// console.log(match)
				// 	if (match && (match[1] || match[2])) {
				// 		return match[1] || match[2]; // 返回签退或签到时间
				// 	}
				// 	return null;
				// }).filter(time => time !== null); // 过滤掉没有匹配到的时间
				
				// if (times.length > 5) {
				// 	times = times.slice(0, 5)
				// }

				if (times.length < 5) {
					// uni.hideLoading()
					uni.showToast({
						title: `读取失败`,
						icon: 'error'
					})
				}

				// const parsedTimes = times.map(time => parseTime(time)); // 将时间字符串转换为分钟数
				let qiandao = 0
				let all = 0
				times.forEach((timeObj, index) => {
					timeObj = timeObj.replace("：", ":")
					const [hours, minutes] = timeObj.split(":").map(Number);
					const current = hours * 60 + minutes; // 将时间转换为分钟数
					switch (index) {
						case 0:
							this.amTime = timeObj
							qiandao = current
							break;
						case 1:
							this.amTime += (" - " + timeObj + " " + this.formatTime(current - qiandao))
							all += current - qiandao
							break;
						case 2:
							this.pmTime = timeObj
							qiandao = current
							break;
						case 3:
							this.pmTime += (" - " + timeObj + " " + this.formatTime(current - qiandao))
							all += current - qiandao
							this.duration = this.formatTime(all)
							break;
						case 4:
							const lastqiantui = times.length > 5 ? " - " + times[5].replace("：", ":") : " - /"
							this.niTime = (timeObj + lastqiantui)
							const last = current + (540 - all)
							const hours = Math.floor(last / 60);
							const mins = String(last % 60).padStart(2, '0');
							this.lastTime = `${hours}:${mins}`;
							break;
					}
				});
			}

		}
	};
</script>

<style lang="scss" scoped>
	.content {
		text-align: center;
		margin-top: 100upx;
		/* #ifdef H5 */
		height: calc(100vh - var(--window-bottom) - var(--window-top));
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
	}

	.mini-btn {
		margin-right: -480upx;
		margin-bottom: 20upx;
	}

	/* ## 时间 ## */

	.SelectTime {
		display: flex;
		flex-direction: grow;
		margin-top: 60upx;
		margin-bottom: 60upx;
	}

	.TimeLabel {
		line-height: 35px;
		width: 0;
		flex-grow: 3;
		text-align: left;
		padding-left: 24px;
	}

	.TimeText {
		width: 0;
		flex-grow: 12;
	}

	.TimeInput {
		height: 100%;
		width: 100px;
		border: #8f8f8f solid 1px;
		border-radius: 5px;
		display: inline-block;
		text-align: center;
		vertical-align: middle;
	}

	.TimeInput-focus {
		border-color: #00aaff;
		color: #00aaff;
	}

	.maohao {
		display: inline-block;
		height: 100%;
		margin: 0 6px;
		line-height: 35px;
		vertical-align: middle;
	}

	.Time-picker {
		color: #8f8f8f;
	}

	.PriceLabel {
		width: 0;
		flex-grow: 2;
		text-align: left;
		padding-left: 28px;
	}
	
	.PriceLabel2 {
		width: 20px;
	}

	.PriceText {
		width: 0;
		flex-grow: 12;
	}

	.radio {
		padding-right: 10px;
	}
</style>